package com.wly.jdbc;

import com.wly.utils.JDBCUtils;

import java.sql.*;
import java.util.Scanner;

/**
 * @Author wly
 * @Create 2023-04-30 11:09
 * @Description:登录练习
 */
public class JDBCDemo6 {

    /**
     * 登录方法
     * @param username
     * @param password
     * @return
     */
    public boolean login(String username, String password){
        if (username == null || password == null){
            return false;
        }
        // 连接数据库，判断是否登陆成功
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        try {
            //获取连接
            conn = JDBCUtils.getConnection();
            String sql = "select * from user where username = '" + username + "' and password = '" + password + "'";
            stmt = conn.createStatement();
            rs = stmt.executeQuery(sql);
            return rs.next();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            JDBCUtils.close(rs, stmt, conn);
        }
        return false;
    }

    /**
     * 使用PreparedStatement的方法
     * @param username
     * @param password
     * @return
     */
    public boolean login2(String username, String password){
        if (username == null || password == null){
            return false;
        }
        // 连接数据库，判断是否登陆成功
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            //获取连接
            conn = JDBCUtils.getConnection();
            String sql = "select * from user where username = ? and password = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, username);
            pstmt.setString(2, password);
            rs = pstmt.executeQuery();
            return rs.next();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            JDBCUtils.close(rs, pstmt, conn);
        }
        return false;
    }

    public static void main(String[] args) {
        //键盘录入，接收用户名，密码
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入用户名：");
        String username = scanner.nextLine();
        System.out.print("请输入密码：");
        String password = scanner.nextLine();
        JDBCDemo6 jdbcDemo6 = new JDBCDemo6();
        boolean flag = jdbcDemo6.login2(username, password);
        if (flag){
            System.out.println("登陆成功！");
        }else {
            System.out.println("登录失败！");
        }
    }
}
